<template>
  <div class="fixed-chat flex">
    <div
      class="chat-main-left"
      :style="{ height: boxHeight + 'px' }"
      @mousedown="startResizeLeft"
    />

    <div class="chat-main-top" @mousedown="startResizeRight" />
    <div
      v-show="isShow"
      class="chat-main"
      :style="{ width: boxWidth + 'px', height: boxHeight + 'px' }"
    >
      <div class="chat-main-header flex justify-between">
        <div class="flex items-center">
          <img
            :class="{ 'bell-icon': loading }"
            src="https://smfg-dev.liteon.com/test_commonFile/icon02.png"
          >
          <span>{{ commonTitle }}</span>
        </div>
        <i class="close" @click="isShow = !isShow">+</i>
      </div>

      <div id="scrollBox" class="chat-main-content">
        <div v-for="(item, index) in chatList" :key="index">
          <div class="my-msg flex justify-end">
            <div class="content">
              {{ item.query }}
            </div>
          </div>
          <div v-show="item.ai_message" class="chat-msg flex justify-start">
            <div class="content">
              <span class="text-block" v-html="item.ai_message" />
            </div>
          </div>
          <div v-show="!item.ai_message" class="dots">
            <div class="dot" />
            <div class="dot" />
            <div class="dot" />
          </div>
        </div>
      </div>

      <div class="chat-main-button">
        <textarea
          v-model="chatContent"
          name="chatContent"
          class="textarea"
          placeholder="Ask any question"
          @keydown="handleKeydown"
        />
        <button
          class="button flex items-center"
          :disabled="loading"
          @click="handleSubmit()"
        >
          <svg
            t="1754011917900"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="5079"
            width="200"
            height="200"
          >
            <path
              d="M605.91 896.85a30 30 0 0 1-25.5-14.21l-167.12-270a30 30 0 0 1 4-36.7l406.2-417.86a30 30 0 0 1 49.85 30.76L634.26 876.7a30 30 0 0 1-25 20 30.41 30.41 0 0 1-3.35 0.15zM476.63 601l121.64 196.49 174-500.64z m-49.48 14.33a29.89 29.89 0 0 1-15.68-4.43L142.1 445.64a30 30 0 0 1 5.59-53.82l683.84-244.4A30 30 0 0 1 862.71 197L448.25 606.67a30 30 0 0 1-21.1 8.66z m-200.3-188.09l196 120.22 301.49-298z"
              fill="#ffffff"
              p-id="5080"
            />
          </svg>
        </button>
      </div>
    </div>

    <div v-show="!isShow" class="flex justify-end" @click="isShow = !isShow">
      <div class="chat-button flex justify-center items-center">
        <img src="https://smfg-dev.liteon.com/test_commonFile/icon01.png">
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LiteonAiChatWidget',
  props: {
    width: {
      type: Number,
      default: 500
    },
    height: {
      type: Number,
      default: 500
    },
    commonTitle: {
      type: String,
      default: 'AI Agent'
    },
    webhookurl: {
      type: String,
      default: ''
    },
    allParams: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      isShow: true,
      chatContent: '',
      chatList: [],
      loading: false,
      boxWidth: this.width,
      boxHeight: this.height,
      resizing: false,
      startX: 0,
      startY: 0
    }
  },
  mounted() {},
  methods: {
    startResizeLeft(e) {
      const startX = e.clientX
      const startWidth = this.boxWidth
      const onMouseMove = (event) => {
        if (event.clientX > 100) {
          const dx = startX - event.clientX
          if (dx + startWidth > 400) {
            this.boxWidth = dx + startWidth
          }
        }
      }
      const onMouseUp = () => {
        document.removeEventListener('mousemove', onMouseMove)
        document.removeEventListener('mouseup', onMouseUp)
      }
      document.addEventListener('mousemove', onMouseMove)
      document.addEventListener('mouseup', onMouseUp)
    },
    startResizeRight(e) {
      const startY = e.clientY
      const startHeight = this.boxHeight
      const onMouseMove = (event) => {
        if (event.clientY > 100) {
          const dx = startY - event.clientY
          if (dx + startHeight > 400) {
            this.boxHeight = dx + startHeight
          }
        }
      }
      const onMouseUp = () => {
        document.removeEventListener('mousemove', onMouseMove)
        document.removeEventListener('mouseup', onMouseUp)
      }
      document.addEventListener('mousemove', onMouseMove)
      document.addEventListener('mouseup', onMouseUp)
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const div = document.getElementById('scrollBox')
        div.scrollTo({
          top: div.scrollHeight,
          behavior: 'smooth'
        })
      })
    },
    handleKeydown(event) {
      if (event.key === 'Enter' && event.shiftKey) {
        // 插入换行符
        this.chatContent += '\n'
        event.preventDefault() // 阻止默认行为
        return false
      }
      if (event.key === 'Enter') {
        if (!this.loading) {
          this.handleSubmit()
        }
        event.preventDefault() // 阻止默认行为
      }
    },
    handleSubmit() {
      const noSpaces = this.chatContent.replace(/\s+/g, '') // "HelloWorld!"
      if (!noSpaces) {
        alert('請輸入您要咨詢的問題')
        return false
      }
      this.loading = true
      const params = {
        query: this.chatContent,
        ai_message: ''
      }
      this.chatList.push(params)
      this.chatContent = ''
      this.scrollToBottom()
      const data = {
        input: params.query,
        ...this.allParams
      }
      fetch(this.webhookurl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      })
        .then((response) => {
          if (!response.ok) {
            // 這裡捕捉 HTTP 錯誤（例如 500）

            setTimeout(() => {
              this.loading = false
              this.chatList.at(-1).ai_message = 'System error'
              this.scrollToBottom()
              throw new Error(`Server Error: ${response.status}`)
            }, 3000)
          }
          return response.json()
        })
        .then((data) => {
          const reply = data.output
          this.chatList.at(-1).ai_message = reply
          this.loading = false
          this.$emit('click', reply)
          this.scrollToBottom()
        }).catch(error => {
          console.error('錯誤：', error.message)

          const reply = error.message
          this.chatList.at(-1).ai_message = reply
          this.loading = false
          this.scrollToBottom()
        })
    }
  }
}
</script>

<style lang="scss" scoped>

.flex {
  display: flex;
}

.justify-center {
  justify-content: center;
}

.justify-between {
  justify-content: space-between;
}

.justify-end {
  justify-content: flex-end;
}

.items-center {
  align-items: center;
}

.fixed-chat {
  display: flex;
  position: fixed;
  z-index: 99999999;
  right: 20px;
  bottom: 20px;
  color: #303133;
  font-family: "Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI",
    Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
    "Segoe UI Emoji", "Segoe UI Symbol";
  .chat-main-left {
    width: 5px;
    height: 100%;
    opacity: 0;
    cursor: ew-resize;
    position: absolute;
    left: 0;
    top: 0;
    background-color: #dcdfe6;
    transition: all 300ms ease-in-out;
    border-radius: 5px;
  }
  .chat-main-left:hover {
    opacity: 1;
  }
  .chat-main-top {
    width: 100%;
    height: 5px;
    opacity: 0;
    cursor: n-resize;
    position: absolute;
    top: 0;
    background-color: #dcdfe6;
    transition: all 300ms ease-in-out;
    border-radius: 5px;
  }
  .chat-main-top:hover {
    opacity: 1;
  }
  .chat-main {
    background-color: #ffffff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
    padding: 14px;
    border-radius: 10px;
    .chat-main-header {
      border-bottom: 1px solid #ebeef5;
      padding-bottom: 10px;
      margin-bottom: 10px;
      img {
        width: 40px;
        height: 40px;
      }
      span {
        font-size: 20px;
        margin-left: 10px;
        font-weight: bold;
      }
      .close {
        display: block;
        font-size: 40px;
        height: 30px;
        line-height: 22px;
        width: 30px;
        text-align: center;
        cursor: pointer;
        transition: all 300ms ease-in-out;
        transform: rotate(45deg); /* 顺时针旋转45度 */
      }
      .close:hover {
        transform: rotate(315deg); /* 顺时针旋转45度 */
      }
    }
    .chat-main-content {
      width: 100%;
      height: calc(100% - 170px);
      overflow-y: auto;
      padding-right: 6px;
      margin-bottom: 10px;
      .my-msg {
        margin-bottom: 10px;
        .content {
          background: #d1f0f3;
          border-radius: 8px;
          padding: 10px;
          text-align: justify;
          font-size: 14px;
          line-height: 22px;
          color: #344050;
        }
      }
      .chat-msg {
        margin-bottom: 10px;
        .content {
          background: #edf2f9;
          border-radius: 8px;
          padding: 10px;
          text-align: justify;
          font-size: 14px;
          line-height: 22px;
          color: #5e6e82;
        }
      }
    }
    .chat-main-button {
      position: relative;
      .textarea {
        border: 1px solid #dcdfe6;
        padding: 10px;
        transition: all 300ms ease-in-out;
        width: 100%;
        height: 100px;
        border-radius: 10px;
        resize: none;
      }
      .textarea:focus {
        border-color: #00acbb;
        outline: none;
        box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
      }
      .textarea::placeholder {
        color: #b6c1d2;
        font-size: 14px;
        font-family: Open Sans;
      }
      .button {
        position: absolute;
        right: 10px;
        bottom: 14px;
        border: 0;
        background-color: #00acbb;
        color: #ffffff;
        cursor: pointer;
        height: 37px;
        width: 37px;
        border-radius: 100%;
        svg {
          width: 30px;
          height: 30px;
        }
      }
    }
  }

  .chat-button {
    width: 80px;
    height: 80px;
    cursor: pointer;
    transition: all 300ms ease-in-out;
    img {
      width: 100%;
      font-weight: bold;
    }
  }
  .chat-button:hover {
    transform: scale(1.05);
  }
}

.dots {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 30px;
}

.dot {
  width: 10px;
  height: 10px;
  margin: 0 5px;
  background-color: #00acbb;
  border-radius: 50%;
  animation: dotPulse 1.5s infinite ease-in-out;
}

.dot:nth-child(2) {
  animation-delay: 0.3s;
}

.dot:nth-child(3) {
  animation-delay: 0.6s;
}

@keyframes dotPulse {
  0%,
  100% {
    opacity: 0.2;
    transform: scale(1);
  }

  50% {
    opacity: 1;
    transform: scale(1.5);
  }
}

.text-block {
  white-space: pre-line;
}

@keyframes ringing {
  10% {
    transform: rotate(15deg);
    transform-origin: center top;
  }
  20% {
    transform: rotate(-15deg);
  }
  30% {
    transform: rotate(20deg);
  }
  40% {
    transform: rotate(-20deg);
  }
  50% {
    transform: rotate(15deg);
  }
  60% {
    transform: rotate(-15deg);
  }
  70% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}
.bell-icon {
  animation: ringing 1s infinite linear;
  transform-origin: center top;
}
</style>
